package org.ii.infrastructure.flow;

import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.webflow.core.FlowException;
import org.springframework.webflow.execution.repository.NoSuchFlowExecutionException;

/**
 * Custom MVC HandlerAdapter
 */
public class FlowHandlerAdapter extends org.springframework.webflow.mvc.servlet.FlowHandlerAdapter {
	@Override
	protected void defaultHandleException(final String flowId, final FlowException e, final HttpServletRequest request, final HttpServletResponse response)
	throws IOException {
		if ( (e instanceof NoSuchFlowExecutionException) && (flowId != null)) {
			sendRedirect(getFlowOutDatedUrl(flowId), request, response);
		} else {
			super.defaultHandleException(flowId, e, request, response);
		}
	}

	/**
	 * Gets the URL for displaying information about the flow being outdated.
	 */
	private String getFlowOutDatedUrl(final String flowId) {
		final int numberOfFolders = flowId.split("/").length;
		String processOutDatedUrl = "";
		for (int i = 1; i < numberOfFolders; i++) {
			processOutDatedUrl = processOutDatedUrl + "../";
		}
		return processOutDatedUrl + "template/flowOutDated";
	}
}
